#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <iostream>

#define NUM 1024

enum Piece
{
    EMPTY,
    BLACK,
    WHITE
};

class Game
{
public:
    Game() : flag(false) 
    {
        memset(data, '\0', NUM);
        for (int i = 0;i < 15;i++)
        {
            for (int j = 0;j < 15;j++)
            {
                board[i][j] = EMPTY;
            }
        }
    }
    ~Game() {}
public:
    // 获取棋子颜色
    void getColor(int sock)
    {
        int color = flag ? 2 : 1;
        Json::StyledWriter writer;
        Json::Value root;
        root["color"] = color;
        std::string result = writer.write(root);
        // 发送数据给客户端
        write(sock, result.c_str(), result.length());
        flag = !flag;
    }

    // 获取坐标
    bool getCoordinate(int sock, int* x, int* y, int* color, const char* data)
    {
        Json::Reader rd;
        Json::Value root;
        rd.parse(data, root);
        if (root["x"].isNull())
        {
            return false;
        }
        *x = root["x"].asInt();
        *y = root["y"].asInt();
        *color = root["color"].asInt();
        return true;
    }

    // 下棋
    bool playChess(int sock, const char* data)
    {
        int x = -1;
        int y = -1;
        int color = -1;
        bool ret = getCoordinate(sock, &x, &y, &color, data);
        if (ret == false)
        {
            return ret;
        }
        board[y][x] = color == 1 ? BLACK : WHITE;
        // 同步数据
        syncData(sock == socks[0] ? socks[1] : socks[0], data);
        return true;
    }

    // 同步数据给另一个客户端
    void syncData(int sock, const char* data)
    {
        write(sock, data, strlen(data));
    }
private:
    Piece board[15][15];
    bool flag;
public:
    std::vector<int> socks;
    char data[NUM];
};